package com.yyhh.helpcall.server;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import androidx.core.app.NotificationCompat;
import com.google.gson.Gson;
import com.rabtman.wsmanager.WsManager;
import com.rabtman.wsmanager.listener.WsStatusListener;
import com.yyhh.helpcall.BuildConfig;
import com.yyhh.helpcall.R;
import com.yyhh.helpcall.activity.CustomerDescActivity;
import com.yyhh.helpcall.activity.MainActivity;
import com.yyhh.helpcall.http.OkHttpUtils;
import com.yyhh.helpcall.http.bean.BaseResponse;
import com.yyhh.helpcall.model.MessageModel;
import com.yyhh.helpcall.utils.AppUtils;
import com.yyhh.helpcall.utils.NetLog;
import com.yyhh.helpcall.utils.ScanCallLogUtils;
import com.yyhh.helpcall.utils.ScanRecordUtils;
import com.umeng.analytics.MobclickAgent;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okio.ByteString;

public class AppService extends Service {

    private boolean call_flag = false;
    private TelephonyManager tm;
    private WsManager wsManager;
    private static final String BASE_URL = BuildConfig.DEBUG ? "ws://gateway.yqtyy.com:8888" : "ws://47.103.86.176:8888" ;

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 201:
                    syncCallLogs();
                    syncRecords();
                    break;
                default:
                    break;
            }
        }
    };

    //同步通话记录
    private void syncCallLogs() {
        ScanCallLogUtils.uploadCallLogs(this);
    }

    //同步录音文件
    private void syncRecords() {
        ScanRecordUtils.uploadRecords(this);
    }

    private void handlerWebSocketMessage(MessageModel msg) {
        switch (msg.type) {
            case "init":
                String client_id = msg.client_id;
                bindClient(client_id);
                break;
            case "call_phone":
                if (!TextUtils.isEmpty(msg.data.phone)) {
                    AppUtils.callPhone(this, msg.data.phone,msg.data.msg_id,"即时消息");
                    //发送事件
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("phone", msg.data.phone);
                    MobclickAgent.onEventObject(getApplicationContext(), "callPhone", map);
                }
                break;
            case "cancel_call":
                AppUtils.endCall(this,msg.data.msg_id,msg.data.phone,"即时消息");
                //发送事件
                HashMap<String, Object> map = new HashMap<>();
                map.put("phone", msg.data.phone);
                MobclickAgent.onEventObject(getApplicationContext(), "cancleCall", map);
                break;
            default:
                break;
        }
    }

    private void bindClient(String clientId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id", clientId);
        OkHttpUtils.getInstance().getApi().bindClient(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponse<Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse<Object> value) {
                        NetLog.d("bindClient success = " + value.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        NetLog.d("bindClient fail");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_OFFHOOK://接听中
                    NetLog.d("接听中" + incomingNumber);
                    call_flag = true;
                    break;
                case TelephonyManager.CALL_STATE_IDLE://空闲
                    NetLog.d("空闲" + incomingNumber);
                    if (call_flag) {
                        call_flag = false;
                        Message msg = Message.obtain();
                        msg.what = 201;
                        handler.sendMessageDelayed(msg, 1000 * 30);
                    }
                    break;
                case TelephonyManager.CALL_STATE_RINGING://来电话
                    NetLog.d("来电话了" + incomingNumber);
                    sendNotification(incomingNumber);
                    break;
                default:
                    break;
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    };

    public AppService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); /** 开启自动外呼系统监听通话 */
        tm.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);//开启监听服务
//        //开启websocket
//        connectingWebSocket();
        //开启首次自动同步
        syncCallLogs();
        syncRecords();
    }

    @Override
    public void onDestroy() {
        NetLog.d("AppService onDestroy");
        try {
            if (phoneStateListener != null && tm != null) {
                tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
            }
            handler.removeCallbacksAndMessages(null);
            stopForeground(true);
//            wsManager.stopConnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        NetLog.d("AppService onStartCommand");
        startForeground(2, createForegroundNotification());
        return START_STICKY;
    }

    private void connectingWebSocket() {
//        String url = "ws://47.103.86.176:8888";
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .pingInterval(10, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
        wsManager = new WsManager.Builder(this)
                .wsUrl(BASE_URL)
                .needReconnect(true)
                .client(okHttpClient)
                .build();
        wsManager.setWsStatusListener(new WsStatusListener() {
            @Override
            public void onOpen(Response response) {
                super.onOpen(response);
                NetLog.d("websocket onOpen");
            }

            @Override
            public void onMessage(String text) {
                NetLog.d("onMessage = " + text);
                super.onMessage(text);
                try {
                    MessageModel message = new Gson().fromJson(text, MessageModel.class);
                    handlerWebSocketMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMessage(ByteString bytes) {
                super.onMessage(bytes);
            }

            @Override
            public void onReconnect() {
                super.onReconnect();
                NetLog.d("websocket onReconnect");
            }

            @Override
            public void onClosing(int code, String reason) {
                super.onClosing(code, reason);
                NetLog.d("websocket onClosing");
            }

            @Override
            public void onClosed(int code, String reason) {
                super.onClosed(code, reason);
                NetLog.d("websocket onClosed");
            }

            @Override
            public void onFailure(Throwable t, Response response) {
                super.onFailure(t, response);
                t.printStackTrace();
                NetLog.d("websocket onFailure");
            }
        });
        wsManager.startConnect();
    }

    /**
     * 创建前台服务的通知
     *
     * @return
     */
    private Notification createForegroundNotification() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 2, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                .setContentTitle("助融通正在运行")
                .setContentText("点击打开应用")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setAutoCancel(false)
                .setContentIntent(pendingIntent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification.setChannelId("foregroundServer");
        }
        return notification.build();
    }

    /**
     * 9以后禁止后台启动activity，所以采用官方推荐的通知启动
     *
     * @param phone
     */
    private void sendNotification(String phone) {
        Intent intent = new Intent(this, CustomerDescActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("phone", phone);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 3, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                .setContentTitle("收到一个新的来电了")
                .setContentText("点击查看客户详情")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setContentIntent(pendingIntent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification.setChannelId("customerDesc");
        }
        manager.notify(3, notification.build());
    }
}
